<?php

require_once(dirname(dirname(dirname(dirname(__FILE__)))) . '/appconf.php');
require_once(dirname(__FILE__) . '/config.php');

class mapi_itrial_member extends Site {

    function setup() {
        $this->run_modes('list_submit_report', 'list_my_report', 'list_member_info', 'login', 'fnb_login', 'facebook_login', 'list_reject_reports', 'list_my_invite', 'confirm_invite', 'apply_with_logout', 'apply_with_login', 'member_like', 'get_share_points', 'my_list');
        $this->start_mode('list_submit_report');
        parent::setup();
    }

    function cgiapp_prerun() {
        $this->Member_center = getModel('Model_MemberCenter');
        $this->Lookup = getModel('Model_Lookup');
        $this->ProductReports = getModel('Model_ProductReports');
        $this->Product = getModel('Model_Product');
        $this->Product_application = getModel('Model_ProductApplication');
        $this->Member = getModel('Model_Member');
        $this->mapi_object = getModel('MAPI_Base');
        $this->email_obj = getLibClass('itrialEmail');
        $this->key = "itrialpw01234567";
        $this->api = $this->param('URL') . 'mapi/itrial/v00.90';
        $this->aes = getLibClass('AES', $this->key);
        $this->super_password = "@)!$2014nmg";
        $this->Points = getModel('Model_Points');
        $this->login_obj = getLibClass('Login');
        $this->height = 300;
        $this->width = 300;
        parent::cgiapp_prerun();
    }

    function action_list_submit_report() {
        $mid = intval($this->get_q('mid', 0, 'int'));
        $page = 1;
        $pagesize = 99;
        $token = $this->get_q('token', '');
        if (!$mid || !$token) {
            return $this->mapi_object->to_json(array(), array(), 0, "用戶id為空或token為空");
        }

        $a_result = $this->submit_reports($mid, $page, $pagesize);

        return $this->mapi_object->to_json($a_result, array(
                    'total' => count($a_result),
                    'pagecount' => 1,
                    'pagesize' => 99,
                    'curpage' => 1
                ));
    }

    function submit_reports($mid, $page, $pagesize) {
        $a_result = array();
        $h_param = array(
            'mid' => $mid,
            'type' => 0,
            'page' => $page,
            'size' => $pagesize
        );

        $submit_reports = $this->Member_center->h_get_report_type($h_param);

        $a_required_field = array('mid', 'my_report_endtime', 'my_report_starttime', 'is_submitted', 'rid');

        if ($submit_reports['result']) {
            foreach ($submit_reports['result'] as $value) {
                $result = array();
                $h_row_application = array();
                $h_row_user_action = array();

                $h_row_product = $this->get_product_by_id($value['product']);

                $h_row_application['id'] = $value['application_id'];

                if ($value['application_id'] == 206) {
                    file_put_contents("sos.txt", '<pre>' . var_export($value, 1) . '</pre>');
                }

                foreach ($a_required_field as $field) {
                    $h_row_application[$field] = $value[$field];
                }
                $h_row_application['accept_endtime'] = "";

                $h_row_application['status_type'] = $value['_bt_s']; //1未開始提交; 2 可以正常提交; 3延期提交(過期7天內);4逾期提交（逾期不能提交）;6編輯（已提交：未通過，未提交：草稿狀態）;
                switch ($value['_bt_s']) {
                    case 1:// google doc 2.0狀態
                        $h_row_user_action = array(
                            'button' => array(),
                            'message' => '已確認邀請，等待提交報告...',
                            'debug_tag' => 'submit_reports_2.0',
                            'remark' => '',
                            'photo_url' => MAPIURL . "remote_photo.png",
                        );
                        break;
                        $h_row_application['status'] = '已接受邀請';
                        $h_row_application['bgcolor'] = '0,0,255';
                        $h_row_application['is_delay'] = 0;
                        $h_row_application['status_photo_url'] = "as9";

                    case 2:// google doc 2.1狀態
                        $h_row_user_action = array(
                            'button' => array(
                                array(
                                    'text' => '提交報告',
                                    'description' => "",
                                    'color' => '0,255,0',
                                    'action' => 'submit_report',
                                    'type' => 'local'
                                )
                            ),
                            'message' => '請提交報告...',
                            'debug_tag' => 'submit_reports_2.1',
                            'remark' => '',
                            'photo_url' => MAPIURL . "remote_photo.png",
                        );
                        $h_row_application['status'] = '未提交報告';
                        $h_row_application['bgcolor'] = '0,0,255';
                        $h_row_application['is_delay'] = 0;
                        $h_row_application['status_photo_url'] = "as115";
                        break;
                    case 3:// google doc 2.5狀態
                        $h_row_user_action = array(
                            'button' => array(
                                array(
                                    'text' => '提交報告',
                                    'description' => "",
                                    'color' => '0,255,0',
                                    'action' => 'submit_report',
                                    'type' => 'local'
                                )
                            ),
                            'message' => '逾期提交，等待提交報告...',
                            'debug_tag' => 'submit_reports_2.5',
                            'remark' => '',
                            'photo_url' => MAPIURL . "remote_photo.png",
                        );
                        $h_row_application['status'] = '未提交報告';
                        $h_row_application['bgcolor'] = '0,0,255';
                        $h_row_application['is_delay'] = 0;
                        $h_row_application['status_photo_url'] = "as115";
                        break;
                    case 4:// google doc 2.9狀態
                        $h_row_user_action = array(
                            'button' => array(),
                            'message' => '逾期未提交...',
                            'debug_tag' => 'submit_reports_2.9',
                            'remark' => '',
                            'photo_url' => MAPIURL . "remote_photo.png",
                        );
                        $h_row_application['status'] = '未提交報告';
                        $h_row_application['bgcolor'] = '0,0,255';
                        $h_row_application['is_delay'] = 0;
                        $h_row_application['status_photo_url'] = "as115";
                        break;
                    case 6:
                        $sub_type = $h_row_application['is_submitted'] ? 2 : 1;
                        $note_arr = array();
                        $button_arr = array();
                        $action_arr = array();

                        $last_time = strtotime($h_row_application['my_report_endtime']) + 3600 * 24 * 7;
                        if ((time() >= strtotime($h_row_application['my_report_starttime']) && time() <= strtotime($h_row_application['my_report_endtime']))) {
                            $date_type = 1;
                            $delay = 0;
                        } elseif (time() > strtotime($h_row_application['my_report_endtime']) && time() <= $last_time) {
                            $date_type = 2;
                            $delay = 1;
                        } elseif (time() > $last_time) {
                            $date_type = 3;
                            $delay = 1;
                        }

                        $note_arr[1][1]['message'] = "已確認邀請，等待提交報告..."; // google doc 2.2狀態
                        $note_arr[1][1]['status'] = "未提交報告"; // google doc 2.2狀態
                        $note_arr[1][1]['status_photo_url'] = "as115";
                        $note_arr[1][1]['debug_tag'] = "submit_reports_2.2"; // google doc 2.2狀態

                        $note_arr[1][2]['message'] = "等待審核..."; // google doc 2.3狀態
                        $note_arr[1][2]['status'] = "等待審核"; // google doc 2.3狀態
                        $note_arr[1][2]['status_photo_url'] = "as3";
                        $note_arr[1][2]['debug_tag'] = "submit_reports_2.3";

                        $note_arr[2][1]['message'] = "逾期提交，等待提交報告..."; // google doc 2.6狀態
                        $note_arr[2][1]['status'] = "未提交報告"; // google doc 2.6狀態
                        $note_arr[2][1]['status_photo_url'] = "as115";
                        $note_arr[2][1]['debug_tag'] = "submit_reports_2.6";

                        $note_arr[2][2]['message'] = "逾期提交，等待審核..."; // google doc 2.8狀態
                        $note_arr[2][2]['status'] = "等待審核"; // google doc 2.8狀態
                        $note_arr[2][2]['status_photo_url'] = "as3";
                        $note_arr[2][2]['debug_tag'] = "submit_reports_2.8";

                        $note_arr[3][1]['message'] = "逾期未提交..."; // google doc 2.10狀態
                        $note_arr[3][1]['status'] = "逾期未提交"; // google doc 2.10狀態
                        $note_arr[3][1]['status_photo_url'] = "as110";
                        $note_arr[3][1]['debug_tag'] = "submit_reports_2.10";

                        $note_arr[3][2]['message'] = "逾期未提交..."; // 理論上不存在
                        $note_arr[3][2]['status'] = "等待審核"; // 理論上不存在
                        $note_arr[3][2]['status_photo_url'] = "as110";
                        $note_arr[3][2]['debug_tag'] = "submit_reports_0.0";

                        $button_arr[1] = "編輯草稿";
                        $button_arr[2] = "編輯報告";

                        $action_arr[1] = "edit_draft";
                        $action_arr[2] = "edit_report";

                        $h_row_user_action = array(
                            'button' => array(
                                array(
                                    'text' => $button_arr[$sub_type],
                                    'description' => "",
                                    'color' => '0,255,0',
                                    'action' => $action_arr[$sub_type],
                                    'type' => 'local'
                                )
                            ),
                            'message' => $note_arr[$date_type][$sub_type]['message'],
                            'debug_tag' => $note_arr[$date_type][$sub_type]['debug_tag'],
                            'remark' => '',
                            'photo_url' => MAPIURL . "images/remote_photo.png",
                        );

                        $h_row_application['status'] = $note_arr[$date_type][$sub_type]['status'];
                        $h_row_application['bgcolor'] = '0,0,255';
                        $h_row_application['is_delay'] = $delay;
                        $h_row_application['status_photo_url'] = $note_arr[$date_type][$sub_type]['status_photo_url'];
                        break;

                    default:
                        break;
                }
                $result['product'] = $h_row_product;
                $result['application'] = $h_row_application;
                $result['user_action'] = $h_row_user_action;
                $a_result[] = $result;
            }
        }
        return $a_result;
    }

    function action_list_reject_reports() {

        $mid = intval($this->get_q('mid', 0, 'int'));
        $page = 1;
        $pagesize = 99;

        $token = $this->get_q('token', '');

        if (!$mid || !$token) {
            return $this->mapi_object->to_json(array(), array(), 0, "用戶id為空或token為空");
        }

        $a_result = $this->reject_reports($mid, $page, $pagesize);
        return $this->mapi_object->to_json($a_result, array(
                    'total' => count($a_result),
                    'pagecount' => 1,
                    'pagesize' => 99,
                    'curpage' => 1
                ));
    }

    function reject_reports($mid, $page, $pagesize) {
        $a_result = array();
        $reject_reports = $this->Member_center->get_reject_report($mid, $page, $pagesize);


        $a_required_field = array('mid', 'my_report_endtime', 'my_report_starttime', 'is_submitted', 'rid');
        if ($reject_reports['result']) {
            foreach ($reject_reports['result'] as $value) {
                $result = array();
                $h_row_application = array();


                $h_row_product = $this->get_product_by_id($value['product']);

                $h_row_application['id'] = $value['application_id'];

                foreach ($a_required_field as $field) {
                    $h_row_application[$field] = $value[$field];
                }

                $h_row_application['accept_endtime'] = "";
                $h_row_application['status_type'] = $value['_bt_s']; //1未開始提交; 2 可以正常提交; 3延期提交(過期7天內);4逾期提交（逾期不能提交）;6編輯（已提交：未通過，未提交：草稿狀態）;
                switch ($value['_bt_s']) {

                    case 6:

                        $note_arr = array();
                        $last_time = strtotime($h_row_application['my_report_endtime']) + 3600 * 24 * 7;
                        if ((time() >= strtotime($h_row_application['my_report_starttime']) && time() <= strtotime($h_row_application['my_report_endtime']))) {
                            $date_type = 1;
                            $delay = 0;
                        } elseif (time() > strtotime($h_row_application['my_report_endtime']) && time() <= $last_time) {
                            $date_type = 2;
                            $delay = 1;
                        } elseif (time() > $last_time) {
                            $date_type = 3;
                            $delay = 1;
                        }

                        $note_arr[1] = "被駁回..."; // google doc 2.4狀態
                        $note_arr[2] = "被駁回..."; // google doc 2.7狀態
                        $note_arr[3] = "被駁回..."; // google doc 2.11狀態
                        $debug_tag[1] = "reject_reports_2.4"; // google doc 2.4狀態
                        $debug_tag[2] = "reject_reports_2.7"; // google doc 2.7狀態
                        $debug_tag[3] = "reject_reports_2.11"; // google doc 2.11狀態


                        $h_row_user_action = array(
                            'button' => array(
                                array(
                                    'text' => '編輯報告',
                                    'description' => "",
                                    'color' => '0,255,0',
                                    'action' => 'edit_report',
                                    'type' => 'local'
                                )
                            ),
                            'message' => $note_arr[$date_type],
                            'debug_tag' => $debug_tag[$date_type],
                            'remark' => '',
                            'photo_url' => MAPIURL . "images/remote_photo.png",
                        );
                        $h_row_application['status'] = '被駁回報告';
                        $h_row_application['bgcolor'] = '0,0,255';
                        $h_row_application['is_delay'] = $delay;
                        $h_row_application['status_photo_url'] = "as105";
                        break;

                    default:
                        break;
                }
                $result['product'] = $h_row_product;
                $result['application'] = $h_row_application;
                $result['user_action'] = $h_row_user_action;
                $a_result[] = $result;
            }
        }
        return $a_result;
    }

    function action_list_my_report() {


        $a_result = array();
        $mid = intval($this->get_q('mid', 0, 'int'));
        $page = intval($this->get_q('page', 1, 'int'));
        $pagesize = intval($this->get_q('pagesize', 10, 'int'));
        $token = $this->get_q('token', '');

        if (!$mid || !$token) {
            return $this->mapi_object->to_json(array(), array(), 0, "用戶id為空或token為空");
        }

        $h_param = array(
            'mid' => $mid,
            'orderby' => "TB1.addtime desc",
            'page' => $page,
            'size' => $pagesize,
            'is_accept' => 1
        );


        $my_reports_res = $this->ProductReports->h_get_reports_list($h_param);


        $my_reports = $this->Member_center->get_my_reports($my_reports_res);

        $a_required_field = array('oid', 'mid', 'agegroup', 'category_score1', 'category_score2', 'category_score3', 'category_score4', 'category_score5', 'category_score6', 'category_score7', 'category_score8', 'is_accept', 'status', 'addtime', 'comments', 'click', 'member_type', 'is_blog', 'username', 'is_publish', 'lastmodify');

        if ($my_reports) {
            foreach ($my_reports as $key => $value) {

                unset($value['report']['type_name']);
                unset($value['report']['time']);
                $a_result[$key]['product'] = $this->get_product_by_id($value['product']['id']);

                foreach ($a_required_field as $field) {
                    $value['report'][$field] = $my_reports_res['result'][$key][$field];
                }

                $m_type = ($value['report']['member_type'] == 5) ? "expert" : "trialist";
                $value['report']['share_url'] = $this->param('URL') . $m_type . "/report-detail-" . $value['report']['oid'] . "-" . $value['report']['id'] . ".html";


                $value['report']['photo_url'] = imore_avatar($my_reports_res['result'][$key]['photo']);
                $value['report']['face_skin'] = $my_reports_res['result'][$key]['body_skin'];
                $value['report']['face_skin_id'] = $my_reports_res['result'][$key]['body_skin_id'];


                if ($my_reports_res['result'][$key]['content_json']) {
                    $a_content = array();
                    $a_json = json_decode($my_reports_res['result'][$key]['content_json'], 1);
                    if ($a_json) {
                        foreach ($a_json as $value_content_json) {
                            $arr = array();
                            //$arr['p'] = $url . showphotoCenter($www . $value['p'], $this->height, $this->width);
                            $arr['p'] = photoResize($value_content_json['p'], '300_200');
                            $arr['bp'] = photoResize($value_content_json['p'], '800_800');
                            $arr['t'] = $value_content_json['t'];
                            $a_content[] = $arr;
                        }
                    }
                }
                $value['report']['content_array'] = $a_content;
                unset($value['report']['content']);
                if ($value['report']['category']) {
                    foreach ($value['report']['category'] as $key_category => $value_category) {
                        unset($value_category['k']);
                        $value['report']['vote_option_array'][$key_category] = $value_category;
                    }
                }

                unset($value['report']['category']);
                $a_result[$key]['report'] = $value['report'];
                $a_result[$key]['user_action'] = array(
                    'button' => array(
                        array(
                            'text' => '查看報告',
                            'description' => "",
                            'color' => '0,255,0',
                            'action' => 'report',
                            'type' => 'local'
                        )
                    ),
                    'message' => '已通過審核...',
                    'debug_tag' => 'my_report_3.0',
                );
                $h_row_application = array();
                $h_row_application['status'] = '已提交報告';
                $h_row_application['bgcolor'] = '0,0,255';
                $h_row_application['status_photo_url'] = "as101";
                $a_result[$key]['application'] = $h_row_application;
            }
        }
        return $this->mapi_object->to_json($a_result, $my_reports_res['pageinfo']);
    }

    function action_list_my_invite() {

        $mid = intval($this->get_q('mid', 0, 'int'));
        $token = $this->get_q('token', '');

        if (!$mid || !$token) {
            return $this->mapi_object->to_json(array(), array(), 0, "用戶id為空或token為空");
        }

        $a_result = $this->my_invite($mid);

        return $this->mapi_object->to_json($a_result, array(
                    'total' => count($a_result),
                    'pagecount' => 1,
                    'pagesize' => 99,
                    'curpage' => 1
                ));
    }

    function my_invite($mid) {
        $this->Member_center->get_expiration_point($mid);
        $this->Member_center->get_unfreeze_point($mid);
        $data = $this->Member_center->productResult($mid, 0);
        //echo '<pre>' . var_export($data, 1) . '</pre>';
        $a_result = array();

        $a_required_field = array('mid', 'status_type', 'accept_endtime');

        if ($data['result']) {
            foreach ($data['result'] as $value) {
                if ($value['status_type'] > 4)
                    continue;
                $result = array();
                $h_row_application = array();

                $h_row_product = $this->get_product_by_id($value['oid']);

                $h_row_application['id'] = $value['application_id'];



                foreach ($a_required_field as $field) {
                    $h_row_application[$field] = $value[$field];
                }
                $h_row_application['my_report_endtime'] = "";
                $h_row_application['my_report_starttime'] = "";
                $h_row_application['is_submitted'] = 0;
                $h_row_application['rid'] = 0;
                $h_row_application['status_type'] = intval($value['status_type']) + 100; //  101;//已申請，未獲邀   102;//已成功獲請，已過期，不可以接受   103;//已成功獲請，可以接受  104;//已成功獲請，已拒絕

                $button_array = array();
                $status = array();
                $status_photo_url = array();
                $button_array[1] = array(
                    'button' => array(),
                    'message' => '已申請，等待邀請...',
                    'debug_tag' => 'my_invite_1.0',
                    'remark' => '',
                    'photo_url' => MAPIURL . "images/remote_photo.png",
                );
                $status[1] = '已申請';
                $status_photo_url[1] = MAPIURL . "images/applied.png";
                $button_array[2] = array(
                    'button' => array(),
                    'message' => '已過確認截止時間...',
                    'debug_tag' => 'my_invite_1.1',
                    'remark' => '',
                    'photo_url' => MAPIURL . "images/remote_photo.png",
                );
                $status[2] = '已成功獲邀';
                $status_photo_url[2] = "as7";
                $button_array[3] = array(
                    'button' => array(
                        array('text' => '同意',
                            'description' => "",
                            'color' => '0,255,0',
                            'action' => $this->api . '/member.php?action=confirm_invite&mid=' . $mid . '&pid=' . $value['oid'] . '&aid=' . $value['application_id'] . '&confirm_status=9',
                            'type' => 'remote'
                        ),
                        array('text' => '拒絕',
                            'description' => "",
                            'color' => '0,0,255',
                            'action' => $this->api . '/member.php?action=confirm_invite&mid=' . $mid . '&pid=' . $value['oid'] . '&aid=' . $value['application_id'] . '&confirm_status=11',
                            'type' => 'remote'
                        )
                    ),
                    'message' => '已成功獲邀，請接受...',
                    'debug_tag' => 'my_invite_1.2',
                    'remark' => '',
                    'photo_url' => MAPIURL . "images/remote_photo.png",
                );
                $status[3] = '已成功獲邀';
                $status_photo_url[3] = "as7";

                $button_array[4] = array(
                    'button' => array(),
                    'message' => '已拒絕邀請...',
                    'debug_tag' => 'my_invite_1.3',
                    'remark' => '',
                    'photo_url' => MAPIURL . "images/remote_photo.png",
                );
                $status[4] = '已拒絕邀請';
                $status_photo_url[4] = "as11";

                $h_row_application['status'] = $status[$value['status_type']];
                $h_row_application['bgcolor'] = '0,0,255';
                $h_row_application['is_delay'] = 0;
                $h_row_application['status_photo_url'] = $status_photo_url[$value['status_type']];

                $result['user_action'] = $button_array[$value['status_type']];
                $result['product'] = $h_row_product;
                $result['application'] = $h_row_application;
                $a_result[] = $result;
            }
            //$data['result'] = $a_result;
        }
        return $a_result;
    }

    function action_list_member_info() {

        $a_result = array();
        $mid = intval($this->get_q('mid', 0, 'int'));

        $token = $this->get_q('token', '');

        if (!$mid || !$token) {
            return $this->mapi_object->to_json(array(), array(), 0, "用戶id為空或token為空");
        }

        $h_param = array(
            'id' => $mid,
        );

        $member_data = $this->Member->h_getMember($h_param);

        //$a_required_field = array('id', 'username', 'email', 'addtime', 'member_type', 'status', 'phone', 'email_status', 'birthday', 'idcard', 'lastmodify', 'points','age');
        $a_required_field = array('id', 'username', 'age', 'points', 'member_type', 'status', 'lastmodify');



        if ($member_data['result']) {
            foreach ($member_data['result'] as $value) {
                $h_row = array();
                foreach ($a_required_field as $field) {
                    $h_row[$field] = $value[$field];
                }

                $h_row['photo_url'] = imore_avatar($value['photo']);

                $h_row['agegroup'] = $h_row['age'];
                unset($h_row['age']);

                $a_result[] = $h_row;
            }
        }

        return $this->mapi_object->to_json($a_result);
    }

    function action_login() {

        return $this->login('imore');
    }

    function action_fnb_login() {

        return $this->login('fnb');
    }

    function login($type = 'imore') {

        $username = $this->get_q('username', '');
        $password = $this->get_q('password', '');

        if ($type == 'imore') {
            $memberData = $this->Member->check_imore_member($username, $this->aes->encrypt($password));
        } elseif ($type == 'fnb') {
            $memberData = $this->Member->check_fnb_member($username, $this->aes->encrypt($password));
        }

        if (!empty($memberData)) {
            if ($memberData['ret'] == 0) {
                $this->Member->login_succeed($memberData); //成功登入imore後，更新登錄時間 或者 插入itrial的member表
                if ($password <> $this->super_password)
                    $this->Points->points_record($memberData['memberInfo']['id'], 'login', "");
            }

            if ($memberData['ret']) {
                return $this->mapi_object->to_json(array(), array(), 0, $memberData['msg']);
            } else {


                $_mem = $this->Member->getMemberCondition($memberData['memberInfo']['id']);

                $_face_skin = empty($_mem['result'][0]['face_skin']) ? $this->Lookup->getLookup('face_skin', 1) : $this->Lookup->getLookup('face_skin', $_mem['result'][0]['face_skin']);
                $memberData['memberInfo']['face_skin'] = $_face_skin['result'][0]['cname'];


                $age = $this->Lookup->getLookup('agegroup');

                $agearr = array();
                if ($age['result']) {
                    foreach ($age['result'] as $value) {
                        $agearr[$value['id']] = $value['name'];
                    }
                }

                $memberData['memberInfo']['agegroup'] = $agearr[getAgeGroup(getAge($memberData['memberInfo']['birthday']))];


                $memberData['memberInfo']['photo_url'] = imore_avatar($memberData['memberInfo']['photo']);
                unset($memberData['memberInfo']['email_receive']);
                return $this->mapi_object->to_json($memberData['memberInfo']);
            }
        } else {
            return $this->mapi_object->to_json(array(), array(), 0, '登入失敗');
        }
    }

    function action_facebook_login() {
        $uid = intval($this->get_q('uid', 0, 'int'));
        $email = $this->get_q('email', '');
        $facebook_accesstoken = $this->get_q('token', '');

        if (!$uid || !$email || !$facebook_accesstoken) {
            return $this->mapi_object->to_json(array(), array(), 0, "facebook id,email,token 為空");
        }

        list($status, $info, $memberData, $fbData) = $this->login_obj->check_fackbook_id_login(array('uid' => $uid, 'email' => $email), $facebook_accesstoken);
        if ($status) {
            if ($memberData) {
                $a_required_field = array('id', 'username', 'points', 'member_type', 'status', 'lastmodify');

                $a_result = array();
                if ($memberData) {
                    $h_row = array();
                    foreach ($a_required_field as $field) {
                        $h_row[$field] = $memberData[$field];
                    }

                    $_mem = $this->Member->getMemberCondition($memberData['id']);

                    $_face_skin = empty($_mem['result'][0]['face_skin']) ? $this->Lookup->getLookup('face_skin', 1) : $this->Lookup->getLookup('face_skin', $_mem['result'][0]['face_skin']);
                    $h_row['face_skin'] = $_face_skin['result'][0]['cname'];


                    $age = $this->Lookup->getLookup('agegroup');

                    $agearr = array();
                    if ($age['result']) {
                        foreach ($age['result'] as $value) {
                            $agearr[$value['id']] = $value['name'];
                        }
                    }

                    $h_row['agegroup'] = $agearr[getAgeGroup(getAge($memberData['birthday']))];
                    $h_row['photo_url'] = imore_avatar($memberData['phpto']);

                    $a_result[] = $h_row;
                }


                return $this->mapi_object->to_json($a_result);
            } else {
                return $this->mapi_object->to_json(array(), array(), 0, "facebook登入成功，但未註冊itrial");
            }
        } else {
            return $this->mapi_object->to_json(array(), array(), 0, "facebook登入失敗");
        }
    }

    function action_confirm_invite() {
        $pid = intval($this->get_q('pid', 0, 'int'));
        $aid = intval($this->get_q('aid', 0, 'int'));
        $mid = intval($this->get_q('mid', 0, 'int'));
        $confirm_status = intval($this->get_q('confirm_status', 0, 'int'));

        $token = $this->get_q('token', '');

        if (!$mid || !$token || !$pid || !$aid || !$confirm_status) {
            return $this->mapi_object->to_json(array(), array(), 0, "用戶id或token或產品id或申請id或確認狀態為空");
        }
        if (!in_array($confirm_status, array(9, 11))) {
            return $this->mapi_object->to_json(array(), array(), 0, "確認狀態有誤");
        }

        $p_application_num = db_query_count('product_application', "id=" . mysql_escape_string($aid) . " and application_status>=9 and  status=1");
        if ($p_application_num > 0) {
            return $this->mapi_object->to_json(array(), array(), 0, "活動已確認或拒絕");
        }

        $product = $this->Product->getProductById($pid);
        if (!$product) {
            return $this->mapi_object->to_json(array(), array(), 0, "沒有該產品");
        }

        if (time() < strtotime($product['apply_starttime'])) {
            return $this->mapi_object->to_json(array(), array(), 0, "活動時間有誤！");
        }
        $product_application = $this->Product_application->getApplicationList(0, 0, "", 1, 1, $aid);
        if ($product_application['result']) {
            $result = $product_application['result'][0];
            if ($result['application_status'] <> 7) {
                return $this->mapi_object->to_json(array(), array(), 0, "審核狀態不正確！");
            } else {
                $m_application_num = db_query_count('member_application', "mid=" . mysql_escape_string($mid) . "  and  status=1 and product=" . mysql_escape_string($pid));
                if ($m_application_num > 0) {
                    return $this->mapi_object->to_json(array(), array(), 0, "活動已確認或拒絕！");
                }
                $res = db_update('product_application', array('application_status' => $confirm_status), 'id=' . mysql_escape_string($aid));
                if ($res) {
                    //$_name = !empty($product['cname']) ? $product['cname'] : $product['name'];
                    $_name = $product['cname'];
                    if ($confirm_status == 9) {
                        $attr = array();
                        $attr['mid'] = $mid;
                        $attr['product'] = $pid;
                        $attr['delivery_status'] = 1;
                        $attr['report_starttime'] = $product['report_starttime'];
                        $attr['report_endtime'] = $product['report_endtime'];
                        $attr['status'] = 1;
                        $attr['addtime'] = date('Y-m-d H:i:s');
                        db_add('member_application', $attr);
                        if ($result['from'] == 1) {
                            $this->Points->points_record($mid, "confirm_product_invite", str_replace("[產品名稱]", $_name, CONFIRM_PRODUCT_INVITE_LANG), $pid, $product['points']);
                        }
                        $str = '你已接受邀請‘' . $product['cname'] . '’，請於‘' . $product['report_endtime'] . '’前提交報告！';

                        $last_time = strtotime($product['my_report_endtime']) + 3600 * 24 * 7;
                        if ((time() >= strtotime($product['my_report_starttime']) && time() <= strtotime($product['my_report_endtime']))) {
                            $button = array(
                                array(
                                    'text' => '下一步',
                                    'description' => "正常提交",
                                    'color' => '0,255,0',
                                    'action' => 'submit_report',
                                    'type' => 'local'
                                )
                            );
                        } elseif ((time() >= strtotime($product['my_report_starttime']) && time() <= $last_time)) {
                            $button = array(
                                array(
                                    'text' => '下一步',
                                    'description' => "逾期提交",
                                    'color' => '0,255,0',
                                    'action' => 'submit_report',
                                    'type' => 'local'
                                )
                            );
                        } elseif (time() > $last_time) {
                            $button = array(
                                array()
                            );
                        } elseif (time() < $product['my_report_starttime']) {
                            $button = array(
                                array()
                            );
                        }
                    } elseif ($confirm_status == 11) {
                        if ($result['from'] == 1) {
                            $this->Points->points_record($mid, "unfreeze_product_invite", str_replace("[產品名稱]", $_name, UNFREEZE_PRODUCT_INVITE_LANG), $pid, $product['points']);
                        }

                        $str = '你已拒絕邀請‘' . $product['cname'] . '’！';
                        $button = array();
                    }


                    $h_row_user_action = array(
                        'button' => $button,
                        'message' => $str,
                        'debug_tag' => 'confirm_invite',
                        'remark' => '',
                        'photo_url' => '',
                    );


                    return $this->mapi_object->to_json(array('user_action' => $h_row_user_action));
                } else {
                    return $this->mapi_object->to_json(array(), array(), 0, "error！");
                }
            }
        } else {
            return $this->mapi_object->to_json(array(), array(), 0, "error！");
        }
    }

    function action_apply_with_login() {
        $mid = intval($this->get_q('mid', 0, 'int'));
        $pid = intval($this->get_q('pid', 0, 'int'));
        $token = $this->get_q('token', '');
        $photo_path = $this->get_q('photo_path', '');
        $reason = $this->get_q('reason', '');
        $global_url = $this->param('URL');


        if (!$mid || !$token || !$pid || !$photo_path || !$reason) {
            return $this->mapi_object->to_json(array(), array(), 0, "用戶id或token或產品id或圖片路徑或申請原因為空");
        }
        $product = $this->Product->getProductById($pid);
        if (!$product) {
            return $this->mapi_object->to_json(array(), array(), 0, "沒有該產品");
        }
        if (time() < strtotime($product['apply_starttime'])) {
            return $this->mapi_object->to_json(array(), array(), 0, "活動時間有誤");
        }
        $member_app_count = db_query_count('product_application', "mid=" . mysql_escape_string($mid) . " and oid=" . mysql_escape_string($pid));
        if ($member_app_count > 0) {
            return $this->mapi_object->to_json(array(), array(), 0, HAS_APPLY);
        }

        $attr = $mjson = array();

        $mjson['photo'] = $photo_path;

        $attr['oid'] = $pid;
        $attr['mid'] = $mid;
        $attr['application_status'] = 1;
        $attr['status'] = 1;
        $attr['body'] = $reason;
        $attr['message_json'] = json_encode($mjson);
        $attr['addtime'] = date('Y-m-d H:i:s');
        $attr['from'] = 2;
        $res = db_add('product_application', $attr);
        if ($res) {
            $_product_one = db_query_one('product', array('field' => 'apply_num', 'where' => 'id=' . $attr['oid']));
            $apply_num = intval($_product_one['result']['apply_num']) + 1;
            db_update('product', array('apply_num' => $apply_num, 'modifiedby' => 1, 'lastmodify' => date('Y-m-d H:i:s')), ' id=' . mysql_escape_string($attr['oid']));

            $emailUrl = $global_url . optimize_url('product', 'invite_inpage', 'mtype=' . $product['member_type'] . '&pid=' . $attr['oid']);

            $name = !empty($product['cname']) ? $product['cname'] : $product['name'];
            if ($product['member_type'] == 5) {
                $this->email_obj->send($attr['mid'], "app_try_fa", array('cname' => $name, 'emailUrl' => $emailUrl));
            } else {

                $this->email_obj->send($attr['mid'], "app_try_fb", array('cname' => $name, 'emailUrl' => $emailUrl));
            }
            return $this->mapi_object->to_json(array(), array(), 1);
        } else {
            return $this->mapi_object->to_json(array(), array(), 0, "error");
        }
    }

    function action_apply_with_logout() {
        $pid = intval($this->get_q('pid', 0, 'int'));
        $email = $this->get_q('email', '');

        if (!$email || !$pid) {
            return $this->mapi_object->to_json(array(), array(), 0, "產品id或email為空");
        }

        $member_num = db_query_count('member_imore', "email='" . mysql_escape_string($email) . "' and  status=1");
        if ($member_num > 0) {
            return $this->mapi_object->to_json(array(), array(), 2, "已存在該email帳號，請登入後申請");
        }

        $product = $this->Product->getProductById($pid);
        if (!$product) {
            return $this->mapi_object->to_json(array(), array(), 0, "沒有該產品");
        }
        if (time() < strtotime($product['apply_starttime'])) {
            return $this->mapi_object->to_json(array(), array(), 0, "活動時間有誤");
        }

        $h_param = array(
            'title' => '使用指引',
            'content' => "
            您好：    
            <br><br>
            您正在申請【" . $product['cname'] . "】
            <br><br> 請點擊鏈結查看使用指引
            <br><br>
            http://itrial.hk/member.php?action=reg&pid=" . $pid,
        );

        $this->email_obj->send($email, "common_email", $h_param);
        return $this->mapi_object->to_json(array(), array(), 1);
    }

    function action_member_like() {

        $mid = intval($this->get_q('mid', 0, 'int'));
        $section_id = intval($this->get_q('section_id', 0, 'int'));
        $section_name = $this->get_q('section_name', '');
        $token = $this->get_q('token', '');
        if (!$mid || !$token || !$section_id || !$section_name) {
            return $this->mapi_object->to_json(array(), array(), 0, "用戶id或token或section id或section name為空");
        }
        if (!in_array($section_name, array('product', 'report', 'comment'))) {
            return $this->mapi_object->to_json(array(), array(), 0, "section name錯誤");
        }

        $type = intval($this->get_q('is_good', 1, 'int')); // 回覆good bad
        $attr = array();
        $attr['section'] = $section_name;
        $attr['mid'] = $mid;
        $attr['sid'] = $section_id;
        $attr['addtime'] = date('Y-m-d H:i:s');
        $c = db_query_count('member_like', "section='" . $section_name . "' and mid=" . mysql_escape_string($mid) . " and sid=" . mysql_escape_string($section_id));
        $recode = $likes = 0;
        $like_field = ($section_name == 'comment' && $type == 2) ? 'unlikes' : 'likes';
        if ($c < 1) {
            $res = db_add('member_like', $attr);
            if ($res > 0) {
                switch ($section_name) {
                    case 'product': $tbn = 'product';
                        break;
                    case 'report': $tbn = 'product_reports';
                        break;
                    case 'comment': $tbn = 'product_reports_comment';
                        break;
                    default : exit;
                }
                $_data = db_query_one($tbn, array('field' => $like_field, 'where' => 'id=' . $section_id . ' and status=1'));
                $likes = intval($_data['result'][$like_field]) + 1;
                $res1 = db_update($tbn, array($like_field => $likes), 'id=' . mysql_escape_string($section_id) . ' and status=1');
                $recode = empty($res1) ? $recode : 1;


                if ($section_name == 'product') {
                    $_data = db_query_one('product', array('field' => 'likes_offset,name,cname', 'where' => 'id=' . $section_id . ' and status=1'));
                    $likes = $likes + intval($_data['result']['likes_offset']);
                    $_name = !empty($_data['result']['cname']) ? $_data['result']['cname'] : $_data['result']['name'];
                    $this->Points->points_record($mid, "like_product", str_replace("[產品名稱]", $_name, LIKE_PRODUCT_LANG));
                } elseif ($section_name == 'report') {
                    $_data = db_query_one('product_reports', array('field' => 'likes_num_base,title,mid', 'where' => 'id=' . $section_id . ' and status=1'));
                    if ($likes == 30)
                        $this->Points->points_record($_data['result']['mid'], "be_liked_report_30", str_replace("[報告名稱]", $_data['result']['title'], BE_LIKED_REPORT_30_LANG));
                    $this->Points->points_record($mid, "like_report", str_replace("[報告名稱]", $_data['result']['title'], LIKE_REPORT_LANG));
                    $likes = $likes + intval($_data['result']['likes_num_base']);
                }
            }
        }
        if ($recode) {
            return $this->mapi_object->to_json(array('likes' => $likes));
        } else {
            return $this->mapi_object->to_json(array(), array(), 0, HAS_LIKES);
        }
    }

    function action_get_share_points() {
        $mid = intval($this->get_q('mid', 0, 'int'));
        $type = $this->get_q('type', ''); //facebook weibo weixin
        $token = $this->get_q('token', '');
        $title = $this->get_q('title', '');
        if (!$mid || !$token || !$type || !$title) {
            return $this->mapi_object->to_json(array(), array(), 0, "用戶id或token或type或者報告標題為空");
        }

        if (!in_array($type, array('facebook', 'weibo', 'weixin'))) {
            return $this->mapi_object->to_json(array(), array(), 0, "section name錯誤");
        }

        $ret = array();
        if ($type == 'facebook') {
            $ret = $this->Points->points_record($mid, 'share_report', $title);
        }

        if ($ret['ret']) {
            return $this->mapi_object->to_json(array(), array(), 1);
        } else {
            return $this->mapi_object->to_json(array(), array(), 0, $ret['reason']);
        }
    }

    function get_product_by_id($id) {
        $url = $this->param('URL');
        $www = $this->param('WWW');


        $kvcobj = getCache('mapi_product_by_id', array('expire' => KVC_EXPIRE));
        $product_by_id = $kvcobj->get('mapi_product_by_id' . $id);
        if (!$product_by_id) {
            $product_by_id_field = array('id', 'name', 'cname', 'brand', 'category', 'quota', 'apply_num', 'click', 'likes', 'body', 'price', 'capacity_trial', 'attribute_label1', 'attribute_value1', 'attribute_label2', 'attribute_value2', 'attribute_label3', 'attribute_value3', 'attribute_label4', 'attribute_value4', 'attribute_label5', 'attribute_value5', 'attribute_label6', 'attribute_value6', 'attribute_label7', 'attribute_value7', 'attribute_label8', 'attribute_value8', 'is_live', 'is_trial', 'status', 'vote_option', 'apply_starttime', 'apply_endtime', 'min_pic_num', 'max_pic_num', 'member_type');
            $a_n_attrubute = array('attribute_value1', 'attribute_value2', 'attribute_value3', 'attribute_value4', 'attribute_value5', 'attribute_value6', 'attribute_value7', 'attribute_value8');
            #评分项目
            $param = array();
            $param['field'] = "id,cname";
            $param['where'] = "status=1";
            $param['order'] = "id asc"; //"id asc"
            $param['group'] = "";
            $param['limit'] = "";
            $param['pagesize'] = "";
            $param['page'] = "";
            $param['join'] = "";
            $param['on'] = "";
            $vote_option_data = db_query_hash('product_vote_option', $param);
            $vote_option_arr = array();
            if ($vote_option_data['result']) {
                foreach ($vote_option_data['result'] as $value) {
                    $vote_option_arr[$value['id']] = $value['cname'];
                }
            }
            $product_by_id = $this->Product->getProductById($id);

            $h_row = array();

            foreach ($product_by_id_field as $field) {
                $h_row[$field] = $product_by_id[$field];
            }

            $n_attrubute = 0;
            foreach ($a_n_attrubute as $value_n_attrubute) {
                if (!empty($product_by_id[$value_n_attrubute]))
                    $n_attrubute+=1;
            }

            #縮略圖
            $h_row['cover_url'] = $url . showphoto($www . $product_by_id['cover'], $this->width, $this->height);

            $h_row['category'] = (intval($h_row['category'])) ? $h_row['category'] : 0;
            #子分類
            $h_row['sub_category'] = $product_by_id['product_layout_category'] ? $product_by_id['product_layout_category'] : 0;
            #屬性數量
            $h_row['n_attrubute'] = $n_attrubute;
            $h_row['lastmodify'] = strtotime($product_by_id['lastmodify']);
            $h_row['share_url'] = $this->param('URL') . "r/p-" . $h_row['id'];

            #圖片數量最少和最多默認值
            $h_row['min_pic_num'] = !empty($h_row['min_pic_num']) ? $h_row['min_pic_num'] : ($h_row['member_type'] == 5 ? 5 : 3);
            $h_row['max_pic_num'] = !empty($h_row['max_pic_num']) ? $h_row['max_pic_num'] : ($h_row['member_type'] == 5 ? 10 : 6);
            #評分項目名稱
            $a_vote_option = array();
            if ($h_row['vote_option']) {
                $vote_option_array = explode(",", $h_row['vote_option']);
                if ($vote_option_array) {
                    foreach ($vote_option_array as $value_option_array) {
                        $a_vote_option[] = $vote_option_arr[$value_option_array];
                    }
                }
            }
            $h_row['vote_option_array'] = $a_vote_option;
            $h_row['vote_option_name'] = implode(",", $a_vote_option);
            $h_row['brand_name'] = $product_by_id['type_name'];

            $product_by_id = $h_row;
            $kvcobj->set('mapi_product_by_id' . $id, $product_by_id);
        }
        return $product_by_id;
    }

    function action_my_list() {
        $mid = intval($this->get_q('mid', 0, 'int'));
        $page = 1;
        $pagesize = 99;
        $result = array();
        $token = $this->get_q('token', '');
        if (!$mid || !$token) {
            return $this->mapi_object->to_json(array(), array(), 0, "用戶id為空或token為空");
        }

        $product = $this->get_product_by_id(9767);

        $application = array(
            'id' => '315',
            'mid' => '20014',
            'status_type' => 000,
            'accept_endtime' => '2013-06-17 17:42:36',
            'my_report_endtime' => '',
            'my_report_starttime' => '',
            'is_submitted' => 0,
            'rid' => 0,
            'status' => 'test',
            'bgcolor' => '0,0,255',
            'is_delay' => 0,
            'status_photo_url' => 'as11',
        );

        $user_action = array(
            'button' => array(
                array(
                    'text' => 'Go to Step1',
                    'description' => "",
                    'color' => '0,255,0',
                    'action' => $this->api . '/game.php?action=step1',
                    'type' => 'remote'
                )
            ),
            'message' => 'Go to Step1',
            'debug_tag' => 'test',
            'remark' => '',
            'photo_url' => '',
        );

        $test_array = array();
        $test_array[0]['user_action'] = $user_action;
        $test_array[0]['product'] = $product;
        $test_array[0]['application'] = $application;

        $a_result_invite = $this->my_invite($mid);
        $a_result_submit = $this->submit_reports($mid, $page, $pagesize);
        $a_result_reject = $this->reject_reports($mid, $page, $pagesize);

        $result = array_merge($test_array, $a_result_invite, $a_result_submit, $a_result_reject);



        return $this->mapi_object->to_json($result, array(
                    'total' => count($result),
                    'pagecount' => 1,
                    'pagesize' => 99,
                    'curpage' => 1
                ));
    }

}

header("Content-type: text/html; charset=utf-8");
$webapp = new mapi_itrial_member();
$webapp->run();
?>
